package com.thinkgem.jeesite.modules.guobo.webservice;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.thinkgem.jeesite.modules.guobo.entity.Rw;
import com.thinkgem.jeesite.modules.guobo.entity.WebServiceResult;
import com.thinkgem.jeesite.modules.guobo.service.RwService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Component("rwWebService")
public class RwWebService {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	RwService rwService;
	
	public String rwFault(String faultMSG){
		logger.info(faultMSG);
		try{
			/*JSONObject jsonObject = JSONObject.fromObject(faultMSG); 
			String code = jsonObject.get("code").toString();
			String status = jsonObject.get("status").toString();
			String faultTime = jsonObject.get("faultTime").toString();
			Rw rw = rwService.getRwByCode(code);
			rw.setStatus(status);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
		    Date date = sdf.parse(faultTime);
		    rw.setFaultTime(date);
		    rwService.save(rw);*/
			
			JSONArray data = JSONArray.fromObject(faultMSG);
			for(int i=0;i<data.size();i++){
			     JSONObject jobj =  (JSONObject) data.get(i);
			     String readerAdr = jobj.get("readerAdr").toString();
			     String status = jobj.get("status").toString();
			     String faultTime = jobj.get("faultTime").toString();
			     logger.info(readerAdr+","+status+","+faultTime);
			     Rw rw = rwService.getRwByAddress(readerAdr);
			     rw.setStatus(status);
			     if(status!=null && !"".equals(status) && !"null".equals(status) && "1".equals(status)){
			    	 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
					 Date date = sdf.parse(faultTime);
			    	 rw.setFaultTime(date);
			     }
			     rwService.save(rw);
			}
		    WebServiceResult result = new WebServiceResult();
			result.setResult("success");
			result.setMessage("读写器状态上传成功");
			JSONObject json = JSONObject.fromObject(result);//将java对象转换为json对象  
	        String str = json.toString();//将json对象转换为字符串  
	        logger.info(str);
			return str;
		}catch(Exception e){
			e.printStackTrace();
			WebServiceResult result = new WebServiceResult();
			result.setResult("fail");;
			result.setMessage("读写器状态上传失败");
			JSONObject json = JSONObject.fromObject(result);//将java对象转换为json对象  
			String str = json.toString();//将json对象转换为字符串  
			logger.info(str);
			return str;
		}
		
	}
}
